package com.tc.itfarm.admin.action.article;

import com.tc.itfarm.admin.biz.LoginBiz;
import com.tc.itfarm.api.common.Codes;
import com.tc.itfarm.api.exception.BusinessException;
import com.tc.itfarm.api.model.Page;
import com.tc.itfarm.api.model.PageList;
import com.tc.itfarm.model.Category;
import com.tc.itfarm.service.CategoryService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;

@Controller
@RequestMapping("/category")
public class ArticleCategoryAction {
	
	@Resource
	private CategoryService categoryService;
	@Resource
	private LoginBiz loginBiz;
	
	@RequestMapping("list")
	public String list(@RequestParam(value = "pageNo", defaultValue="1", required = true) Integer pageNo,
			Model model) {
		
		Page page = new Page(pageNo, Codes.COMMON_PAGE_SIZE);
		PageList<Category> categoyPageList = categoryService.selectByPage(page);
		model.addAttribute("categorys", categoyPageList.getData());
		model.addAttribute("page", categoyPageList.getPage());
		return "admin/article/category";
	}
	
	@RequestMapping("addCategoryUI")
	public String addCategoryUI() {
		return "admin/article/addcategory";
	}

	@RequestMapping("editCategoryUI")
	public String editCategoryUI(Model model, @RequestParam(value ="recordId", required = true) Integer id) {
		Category category = categoryService.select(id);
		model.addAttribute("category", category);
		return "admin/article/addcategory";
	}
	
	
	@RequestMapping("addCategory")
	public String category(Category category,
			Model model) {
		category.setUserId(loginBiz.getCurUser().getRecordId());
		try {
			categoryService.save(category);
		} catch (BusinessException e) {
			model.addAttribute("name", category.getName());
			model.addAttribute("description", category.getDescription());
			model.addAttribute("msg", e.getMessage());
			return "admin/article/addcategory";
		}
		return "redirect:list.do";
	}
	
	@RequestMapping("deleteCategory")
	public String category(@RequestParam(value = "recordId", defaultValue="", required = true) Integer recordId) {
		categoryService.delete(recordId);
		return "redirect:list.do";
	}
}
